<template>
	<cmDialog v-model="state.modelValue" :modal-title="'新增/编辑'" model-width="1200px">
		<el-form ref="baseFormRef" :model="baseForm" :rules="baseRules" label-width="200px">
			<el-tabs v-model="activeName" class="tabs" @tab-click="handleClick" @tab-change="handleChange">
				<el-tab-pane label="标准信息" name="biaozhun">
					<div class="content">
						<biaozhunxinxi ref="biaozhunxinxiRef" @update:message="sumbitApi"></biaozhunxinxi>
					</div>
				</el-tab-pane>

				<el-tab-pane label="主编单位" name="zhubian" :disabled="state.isDisableFlag">
					<div class="content">
						<zhubiandanwei ref="zhubiandanweiRef" :datainfo="state.firstBiaozhunInfo"></zhubiandanwei>
					</div>
				</el-tab-pane>
				<el-tab-pane label="主要起草人" name="qicaoren" :disabled="state.isDisableFlag">
					<div class="content">
						<zhuyaoqicao ref="zhuyaoqicaoRef" :datainfo="state.firstBiaozhunInfo"></zhuyaoqicao>
					</div>
				</el-tab-pane>
				<el-tab-pane label="主要审查人" name="shencharen" :disabled="state.isDisableFlag">
					<zhuyaoshencha ref="zhuyaoshenchaRef" :datainfo="state.firstBiaozhunInfo"></zhuyaoshencha>
				</el-tab-pane>
				<el-tab-pane label="条文" name="tiaowen" :disabled="state.isDisableFlag">
					<tiaowen ref="tiaowenRef" :datainfo="state.firstBiaozhunInfo"></tiaowen>
				</el-tab-pane>
				<el-tab-pane label="引用标准" name="yinyong" :disabled="state.isDisableFlag">
					<yingyongbiaozhun ref="yingyongbiaozhunRef" :datainfo="state.firstBiaozhunInfo"></yingyongbiaozhun>
				</el-tab-pane>
				<el-tab-pane label="应用项目" name="xiangmu" :disabled="state.isDisableFlag">
					<yingyongxiangmu ref="xiangmuRef" :datainfo="state.firstBiaozhunInfo"></yingyongxiangmu>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		<template #footer>
			<div class="dialog-foot">
				<el-button v-if="Number(currIndex) !== 0" @click="previousHandle">上一步</el-button>
				<!-- <el-button type="primary" @click="handleSubmit">提交</el-button> -->
				<el-button v-if="currIndex !== 6" @click="nextHandle">下一步</el-button>
			</div>
		</template>
	</cmDialog>
</template>
<script setup lang="ts">
// import { filePreviewByName } from '@/api/sys/upload'
// import { Drafter, Unit, UploadFile } from '@/interface/declare'

import { useUserStore } from '@/store/modules/user'
import type { FormInstance, TabPaneName, TabsPaneContext } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'

import cmDialog from '@/components/cm-dialog/index.vue'

import biaozhunxinxi from './bz.vue'
import tiaowen from './tw.vue'
import yingyongbiaozhun from './yybz.vue'
import yingyongxiangmu from './yyxm.vue'
import zhubiandanwei from './zbdw.vue'
import zhuyaoqicao from './zyqcr.vue'
import zhuyaoshencha from './zyscr.vue'

import { listCategoryAndLabelApi } from '@/api/standard/maintenance/index'
import { nextTick } from 'vue'

const userStore = useUserStore()
// 上一步 和 下一步操作
const currIndex = ref(0)
const tabsArr = [
	{
		name: 'biaozhun',
		value: 1
	},
	{
		name: 'zhubian',
		value: 2
	},
	{
		name: 'qicaoren',
		value: 3
	},
	{
		name: 'shencharen',
		value: 4
	},
	{
		name: 'tiaowen',
		value: 5
	},
	{
		name: 'yinyong',
		value: 6
	},
	{
		name: 'xiangmu',
		value: 7
	}
]
const props = defineProps({
	editId: {
		// 编制申报传递参数id、列表编辑id
		type: String,
		default: ''
	}
})
const emit = defineEmits(['submit-success', 'dialog-cancel'])
const activeName = ref('biaozhun')
const biaozhunxinxiRef = ref()
const zhubiandanweiRef = ref()
const zhuyaoqicaoRef = ref()
const zhuyaoshenchaRef = ref()
const tiaowenRef = ref()
const yingyongbiaozhunRef = ref()
const xiangmuRef = ref()

const state = reactive({
	modelValue: false,
	isUpdateFlag: false,
	queryParams: {
		id: ''
	},
	basicCategories: [],
	specialCategories: [],
	labels: [],

	isDisableFlag: false, // 如果标准id不行就不能点击下一个
	// 标准信息infor
	firstBiaozhunInfo: {}
})

watch(
	() => state.modelValue,
	newVal => {
		if (!newVal) {
			currIndex.value = 0
			activeName.value = 'biaozhun'
		}
		if (newVal) {
			state.queryParams.id = props.editId
			initCategory()
		}
	}
)
// 监听tabs切换获取数据
watch(
	() => activeName.value,
	(newVal, oldVal) => {
		if (newVal == 'zhubian') {
			// currIndex.value = 0
			zhubiandanweiRef.value.initZbdw()
		} else if (newVal == 'qicaoren') {
			// currIndex.value = 1
			zhuyaoqicaoRef.value.initQcr()
		} else if (newVal == 'shencharen') {
			// currIndex.value = 2
			zhuyaoshenchaRef.value.initScr()
		} else if (newVal == 'tiaowen') {
			// currIndex.value = 3
			tiaowenRef.value.initTw()
		} else if (newVal == 'yinyong') {
			// currIndex.value = 4
			yingyongbiaozhunRef.value.inityybz()
		} else if (newVal == 'xiangmu') {
			// currIndex.value = 5
			xiangmuRef.value.inityyxm()
		}
	}
)
// const dialogState = computed({
// 	get: () => props.modelValue,
// 	set: val => emit('update:modelValue', val)
// })
// 所有的分类字典表
const initCategory = async () => {
	await listCategoryAndLabelApi({}).then(res => {
		state.basicCategories = res.data.basicCategories // 基础分类
		state.specialCategories = res.data.specialCategories // 专题分类
		state.labels = res.data.labels

		biaozhunxinxiRef.value.init(state.basicCategories, state.specialCategories, state.labels)
	})
}

const init = (isUpdate: Boolean, row: any) => {
	state.modelValue = true
	state.isUpdateFlag = Boolean(isUpdate)
	if (isUpdate) {
		// 新增
		state.isDisableFlag = true
	} else {
		// 编辑
		setTimeout(() => {
			biaozhunxinxiRef.value.initDetail(row)
			state.firstBiaozhunInfo.id = row.id
		}, 1000)
		state.isDisableFlag = false
	}
}

// 表单提交数据
const sumbitApi = async data => {
	// 标准信息提交好，代表id出现了，那后面就可以按照id去看后面的数据
	if (data && data.id) {
		nextTick(() => {
			state.isDisableFlag = false // 代表后续可以点击
		})
		state.firstBiaozhunInfo = data
	}
}
// 上一步，下一步操作
const handleClick = (tab: TabsPaneContext, event: Event) => {
	console.log(tab)
}
const handleChange = (name: TabPaneName) => {
	if (name == 'biaozhun') {
		currIndex.value = 0
	} else if (name == 'zhubian') {
		currIndex.value = 1
	} else if (name == 'qicaoren') {
		currIndex.value = 2
	} else if (name == 'shencharen') {
		currIndex.value = 3
	} else if (name == 'tiaowen') {
		currIndex.value = 4
	} else if (name == 'yinyong') {
		currIndex.value = 5
	} else if (name == 'xiangmu') {
		currIndex.value = 6
	}
}
const nextHandle = () => {
	if (currIndex.value < tabsArr.length - 1) {
		if (currIndex.value == 0) {
			ElMessageBox.confirm('点击下一步之前需要保存，否则置空?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				if (!state.isDisableFlag) {
					currIndex.value++
					activeName.value = tabsArr[currIndex.value]['name']
				} else {
					ElMessage.error('提交标准信息之后才能获取')
				}
			})
		} else {
			currIndex.value++
			activeName.value = tabsArr[currIndex.value]['name']
		}
	} else {
		console.log('已经是最后一项了')
	}
}
const previousHandle = () => {
	if (currIndex.value > 0) {
		currIndex.value--
		activeName.value = tabsArr[currIndex.value]['name']
	} else {
		console.log('已经是第一项了')
	}
}

const baseFormRef = ref<FormInstance>()
const baseForm = ref({
	standardProjectInfo: {
		id: '',
		standardProjectName: '',
		applyYear: '',
		projectSelfFunding: '',
		projectFunding: '',
		responsibleOrg: '',
		contactName: '',
		contactTel: '',
		contactAddress: '',
		contactEmail: '',
		professionalKeyFields: '',
		applyStage: ''
	}
})

const rules = reactive<any>({})
const baseRules = computed(() => ({
	standardProjectInfo: {
		standardProjectName: [{ required: true, message: '请输入', trigger: 'blur' }],
		applyYear: [{ required: true, message: '请选择', trigger: 'change' }],
		projectSelfFunding: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{
				pattern: /^-?\d+(\.\d+)?$/,
				message: '请输入有效的数字',
				trigger: 'blur'
			}
		],
		projectFunding: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{
				pattern: /^-?\d+(\.\d+)?$/,
				message: '请输入有效的数字',
				trigger: 'blur'
			}
		],
		responsibleOrg: [{ required: true, message: '请选择', trigger: 'change' }],
		contactName: [{ required: true, message: '请输入', trigger: 'blur' }],
		contactTel: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ pattern: /^1\d{10}$/, message: '请输入有效的手机号', trigger: 'blur' }
		],
		contactAddress: [{ required: true, message: '请输入', trigger: 'blur' }],
		contactEmail: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{
				pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
				message: '请输入有效的邮箱地址',
				trigger: 'blur'
			}
		],
		professionalKeyFields: [{ required: true, message: '请选择', trigger: 'change' }]
	}
}))

// watch(
// 	() => props.editId,
// 	newVal => {
// 		if (newVal) {
// 			getDeclare({
// 				id: newVal
// 			}).then(res => {
// 				let data = res.data
// 				data.standardProjectInfo.professionalKeyFields = data.standardProjectInfo.professionalKeyFields
// 					? data.standardProjectInfo.professionalKeyFields.split(',')
// 					: ''
// 				data.standardProjectInfo.responsibleOrg = data.standardProjectInfo.responsibleOrg ? data.standardProjectInfo.responsibleOrg.split(',') : ''
// 				baseForm.value = data
// 				unitList.value = []
// 				data.projectEditorUnitList.forEach((i: any, index: number) => {
// 					unitList.value.push({
// 						id: i.id,
// 						orderName: index + 1,
// 						editorUnitName: i.editorUnitName,
// 						contacts: i.contacts,
// 						contactsTel: i.contactsTel,
// 						contactsEmail: i.contactsEmail,
// 						contactsAddress: i.contactsAddress,
// 						responsiblePerson: i.responsiblePerson,
// 						responsiblePersonTel: i.responsiblePersonTel,
// 						responsiblePersonEmail: i.responsiblePersonEmail,
// 						userCode: i.userCode,
// 						remark: i.remark,
// 						unitType: i.unitType,
// 						index: index
// 					})
// 				})
// 				drafterList.value = []
// 				data.projectMainDrafterList.forEach((i: any, index: number) => {
// 					drafterList.value.push({
// 						id: i.id,
// 						mainDrafterName: i.mainDrafterName,
// 						mainDrafterTitle: i.mainDrafterTitle,
// 						mainDrafterCompany: i.mainDrafterCompany,
// 						responsibleContent: i.responsibleContent,
// 						drafterRemark: i.drafterRemark,
// 						remark: i.remark,
// 						index: index
// 					})
// 				})
// 				uploadPdfList.value = data.filesRecordList.filter((i: any) => i.extCode === 'ProjectProposalStampedVersion') || []
// 				uploadList.value = data.filesRecordList.filter((i: any) => i.extCode === 'StandardApplyOtherFiles') || []
// 				uploadShowPdfList.value = JSON.parse(JSON.stringify(uploadPdfList.value))
// 				uploadShowList.value = JSON.parse(JSON.stringify(uploadList.value))
// 				if (uploadShowPdfList.value.length > 0) {
// 					uploadShowPdfList.value.forEach((i: any) => {
// 						i.name = i.fileRealName
// 					})
// 				}
// 				if (uploadShowList.value.length > 0) {
// 					uploadShowList.value.forEach((i: any) => {
// 						i.name = i.fileRealName
// 					})
// 				}
// 				auditRecordList.value = data.auditRecordList
// 			})
// 		} else {
// 			baseFormRef.value?.resetFields()
// 			unitList.value = []
// 			drafterList.value = []
// 			uploadPdfList.value = []
// 			uploadList.value = []
// 			uploadShowPdfList.value = []
// 			uploadShowList.value = []
// 			baseForm.value.standardProjectInfo.id = ''
// 			baseForm.value.standardProjectInfo.applyStage = ''
// 			baseForm.value.standardProjectProposal.id = ''
// 			baseForm.value.projectEditorUnitList = []
// 			baseForm.value.projectMainDrafterList = []
// 			baseForm.value.filesRecordList = []
// 		}
// 	},
// 	{ immediate: true }
// )

const handleAddUnit = () => {
	unitCount.value = unitList.value.length
	const mainUnitCount = unitList.value.filter(unit => unit.unitType == 0).length
	if (mainUnitCount >= 2) {
		ElMessageBox.confirm('根据编制要求主编单位原则上不超过2家！', '温馨提示', {
			confirmButtonText: '继续增加',
			cancelButtonText: '关闭',
			type: 'warning'
		})
			.then(() => {
				showAddUnit.value = true
			})
			.catch(() => {})
	} else {
		showAddUnit.value = true
	}
}

const handleAddDrafter = () => {
	if (drafterList.value.length >= 25) {
		ElMessageBox.confirm('根据编制要求，起草人原则上不超过25个！', '温馨提示', {
			confirmButtonText: '继续增加',
			cancelButtonText: '关闭',
			type: 'warning'
		})
			.then(() => {
				showAddDrafter.value = true
			})
			.catch(() => {})
	} else {
		showAddDrafter.value = true
	}
}

const submitUnit = (e: Unit) => {
	showAddUnit.value = false
	const index = e.index ?? -1
	if (index > -1) {
		unitList.value[index] = e
	} else {
		unitList.value.push({ ...e })
	}
}

const handleEditUnit = (e: Unit, i: number) => {
	showAddUnit.value = true
	e.index = i
	unitInfo.value = e
}

const handleDeleteUnit = (i: number) => {
	ElMessageBox.confirm('确定要删除吗?', '提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		unitList.value.splice(i, 1)
	})
}

const submitDrafter = (e: Drafter) => {
	showAddDrafter.value = false
	const index = e.index ?? -1
	if (index > -1) {
		drafterList.value[index] = e
	} else {
		drafterList.value.push({ ...e })
	}
}

const closeUnitDialog = () => {
	activeName.value = 'base'
	unitCount.value = 0
	unitInfo.value = {
		orderName: 1,
		editorUnitName: '',
		contacts: '',
		contactsTel: '',
		contactsEmail: '',
		contactsAddress: '',
		responsiblePerson: '',
		responsiblePersonTel: '',
		responsiblePersonEmail: '',
		userCode: '',
		remark: '',
		unitType: 0,
		index: -1
	}
}

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
}

defineExpose({
	init
})
</script>
<style lang="scss" scoped>
.tabs :deep(.el-tabs__nav-wrap) {
	display: flex;
	justify-content: center;
	margin-top: 10px;
}

.content {
	padding: 0 20px;
}

.dialog-foot {
	display: flex;
	justify-content: center;
	margin-bottom: 10px;
	padding-bottom: 20px;
}

:deep(.el-form-item__label) {
	line-height: 1.5;
}

:deep(.custom-label .el-form-item__label) {
	line-height: 32px;
}
</style>
